package com.lc.zpyh.ui.activity.supermarket;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.request.SelectCommonRemarkApi;
import com.lc.zpyh.http.response.SelectCommonRemarkBean;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RemarksActivity extends AppActivity {
    @BindView(R.id.publish_ed_desc)
    EditText mPublishEdDesc;
    @BindView(R.id.publish_text_num)
    TextView mPublishTextNum;
    @BindView(R.id.rv_remarks)
    RecyclerView rvRemarks;
    //输入框初始值
    private int num = 0;
    //输入框最大值
    public int mMaxNum = 50;
    List<SelectCommonRemarkBean.ListBean> dataBeanList=new ArrayList<>();
    private Map<Integer, String> specificationMap = new HashMap<>();

    private BaseQuickAdapter<SelectCommonRemarkBean.ListBean, BaseViewHolder> commonNameadapter;
    private String commonName;
    private String beizhu;
    private String merchantId;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_remarks;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        beizhu = getIntent().getStringExtra("beizhu");
        merchantId = getIntent().getStringExtra("merchantId");
        if (!beizhu.equals("无")){
            mPublishEdDesc.setText(beizhu);
            mPublishTextNum.setText(beizhu.length()+"/50");
        }

        mPublishEdDesc.addTextChangedListener(new TextWatcher() {
            //记录输入的字数
            private CharSequence wordNum;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //实时记录输入的字数
                wordNum = s;
            }

            @Override
            public void afterTextChanged(Editable s) {

                    int number = num + s.length();
                    //TextView显示剩余字数
                    mPublishTextNum.setText("" + number + "/50");
                    selectionStart = mPublishEdDesc.getSelectionStart();
                    selectionEnd = mPublishEdDesc.getSelectionEnd();
                    //判断大于最大值
                    if (wordNum.length() > mMaxNum) {
                        //删除多余输入的字（不会显示出来）
//                        s.delete(selectionStart - 1, selectionEnd);
                        s.delete(mMaxNum, s.length());
                        int tempSelection = selectionEnd;
                        mPublishEdDesc.setText(s);
                        mPublishEdDesc.setSelection(tempSelection);//设置光标在最后
                        //吐司最多输入50字
                        toast("最多输入50字");
                    }



            }
        });
        searchrecords();
    }

    private void searchrecords() {
        EasyHttp.post(this)
                .api(new SelectCommonRemarkApi()).request(new HttpCallback<SelectCommonRemarkBean>(this) {

            @Override
            public void onSucceed(SelectCommonRemarkBean data) {
                if (data.getCode()==0){
                    dataBeanList.clear();
                    dataBeanList.addAll(data.getList());
                    FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
                    layoutManager.setFlexDirection(FlexDirection.ROW);
                    layoutManager.setJustifyContent(JustifyContent.FLEX_START);
                    rvRemarks.setLayoutManager(layoutManager);
                    commonNameadapter = new BaseQuickAdapter<SelectCommonRemarkBean.ListBean, BaseViewHolder>
                            (R.layout.item_home_search, data.getList()) {

                        @Override
                        protected void convert(BaseViewHolder baseViewHolder, SelectCommonRemarkBean.ListBean dataBean) {
                            baseViewHolder.setText(R.id.tv_search_records, dataBean.getCommonlyUsedContent());
                            if (dataBean.isGrop()) {
                                baseViewHolder.setBackgroundResource(R.id.ll_bg, R.mipmap.bg_true_s);

                            }else {
                                baseViewHolder.setBackgroundResource(R.id.ll_bg, R.drawable.bg_verification_code);
                            }
                        }


                    };
                    commonNameadapter.setOnItemClickListener(new OnItemClickListener() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                            specificationMap.clear();
                            SelectCommonRemarkBean.ListBean bean = dataBeanList.get(position);
                            List<SelectCommonRemarkBean.ListBean> goodsAttrBeanList = dataBeanList;
                            if (goodsAttrBeanList != null && goodsAttrBeanList.size() > 0) {
                                for (int i = 0; i < goodsAttrBeanList.size(); i++) {
                                    if (i == position) {
                                        boolean isSelect = goodsAttrBeanList.get(i).isGrop();
                                        goodsAttrBeanList.get(i).setGrop(!isSelect);
                                    }
                                }
                            }
                            commonName = dataBeanList.get(position).getCommonlyUsedContent();
                            if (bean.isGrop()){

                                specificationMap.put(position, commonName);

                            }else {
                                specificationMap.remove(position, commonName);

                            }
                            String specification = "";
                            for (Integer key : specificationMap.keySet()) {
                                specification = specification + specificationMap.get(key) + "、";
                            }
                            mPublishEdDesc.setText(mPublishEdDesc.getText().toString()+specification);
                            commonNameadapter.notifyDataSetChanged();
                        }
                    });
                    rvRemarks.setAdapter(commonNameadapter);
                }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });


    }


    @OnClick(R.id.tv_sure)
    public void onClick() {
        Intent intent =getIntent();
        Bundle bundle =new Bundle();
        bundle.putString("Remark",mPublishEdDesc.getText().toString());
        bundle.putString("merchantId",merchantId);
        intent.putExtras(bundle);
        setResult(666,intent);
        finish();
    }
}
